// 新闻新增
import 'braft-editor/dist/index.css';
import React from 'react';
import { observer, useLocalStore } from 'mobx-react-lite';
import { useLocation, useHistory } from 'react-router';
import { parse } from 'qs';
import { Card, Form, Row, Col, Button, Input, message } from 'antd';
import BraftEditor from 'braft-editor';
import AjaxSelect from '~/components/AjaxSelect';
import { genValidConfig } from './pageConfig';
import * as addApi from '~/apis/news/addApi';
import { PictureUploader, formatFileList } from '~/components/PictureUploader';
import { RichText } from '~/components/RichText';
import './index.local.sass';

const cardConfig = {
  size: 'small' as const,
  bordered: false,
};

const FormItem = Form.Item;
const { TextArea } = Input;

const formItemLayout = {
  wrapperCol: { span: 20 },
};

const AddOrEditNews = observer(() => {
  const location = useLocation();
  const history = useHistory();
  const querryParams = parse(location.search, { ignoreQueryPrefix: true });
  const state = useLocalStore(() => ({
    id: querryParams.id || '',
    loading: false,
    editorState: BraftEditor.createEditorState('<p></b></p>'), // 设置编辑器初始内容
    outputHTML: '',
  }));

  const [form] = Form.useForm();

  // 获取表单数据
  const getFormValus = () => form.validateFields().then((values: any) => {
    const params = {
      id: state.id,
      ...values,
      mainPicUrl: values.imgList ? values.imgList.map((v: any) => v.response.data).toString() : '',
    };
    delete params.imgList;
    return params;
  });

  const onSubmit = () => {
    getFormValus().then((params) => {
      const _params = {
        ...params,
        allContent: state.outputHTML,
      };

      addApi.addNews(_params).then(() => {
        message.success('success');
        history.push('/news/my');
      });
    }).catch(() => {
      message.error('validation error');
    });
  };

  const onSaveAndClose = () => {
    history.push('/news/my');
  };

  // 表单填充
  const fillForm = (formData: any) => {
    const {
      title,
      authors,
      countryId,
      imgUrl,
      summary,
      allContent = '',
    } = formData;

    form.setFieldsValue({
      title,
      authors,
      countryId,
      summary,
      imgList: formatFileList(imgUrl ? imgUrl.split(',') : []),
    });

    // 富文本内容填充
    state.editorState = BraftEditor.createEditorState(allContent);
  };

  // initForm
  const initForm = (id: string) => {
    addApi.getNewsInfo(id).then((res) => {
      fillForm(res.data);
    });
  };

  // 子传父
  const changText = (value: any) => {
    state.editorState = value;
    if (value.toHTML() === '<p></p>') {
      state.outputHTML = '';
    } else {
      state.outputHTML = value.toHTML();
    }
  };

  React.useEffect(() => {
    if (state.id) {
      initForm(state.id);
    }
  }, []);

  return (
    <div>
      <Card {...cardConfig} className="search-card">
        <Form form={form} layout="vertical" className="w-11/12">
          {/* line 1 */}
          <Row>
            <Col span={8}>
              <FormItem
                label="Title"
                name="title"
                rules={genValidConfig('Name')}
                {...formItemLayout}
              >
                <Input
                  allowClear={true}
                  placeholder="Please input"
                />
              </FormItem>
            </Col>
          </Row>
          {/* line 2 */}
          <Row>
            <Col span={8}>
              <FormItem
                label="Authors"
                name="authors"
                {...formItemLayout}
              >
                <Input
                  allowClear={true}
                  placeholder="Please input"
                />
              </FormItem>
            </Col>
          </Row>
          {/* line 3 */}
          <Row>
            <Col span={8}>
              <FormItem
                name="countryId"
                label="Country/Region"
                rules={genValidConfig('Country/Region')}
                {...formItemLayout}
              >
                <AjaxSelect
                  placeholder="Please select"
                  type="countryList"
                />
              </FormItem>
            </Col>
          </Row>
          {/* line 4 */}
          <Row>
            <Col span={8}>
              <FormItem
                name="imgList"
                label="Attachments"
              >
                <PictureUploader
                  max={1}
                  accept="image/jpeg,image/bmp,image/png"
                />
              </FormItem>
              <p className="mt-2 text-xs cor-grey">Support JPG JPEG PNG BMP only</p>
            </Col>
          </Row>
          {/* line 5 */}
          <Row className="mt-6">
            <Col span={8}>
              <FormItem
                label="Summary"
                name="summary"
                rules={genValidConfig('Summary')}
                {...formItemLayout}
              >
                <TextArea rows={4}/>
              </FormItem>
            </Col>
          </Row>
          {/* line 6 */}
          <Row>
            <Col span={24}>
              <FormItem
                name="allContent"
                label="Content"
                rules={[{
                  required: true,
                  validator: () => {
                    if (!state.outputHTML) {
                      return Promise.reject(new Error('Content is required'));
                    }
                    return Promise.resolve();
                  },
                  message: 'Content is required',
                }]}
              >
                <div className="editor-wrapper">
                  <RichText onChange={(value: any) => changText(value)} value={state.editorState}/>
                </div>
              </FormItem>
            </Col>
          </Row>
        </Form>
      </Card>

      <div>
        <Button
          type="primary"
          className="mr-2"
          onClick={onSubmit}
        >
          Submit & Review
        </Button>

        <Button
          className="mr-2"
          onClick={onSaveAndClose}
        >
          Close
        </Button>
      </div>
    </div>
  );
});

export default AddOrEditNews;
